<!--
  下拉选项列表，可通过输入关键字，请求接口数据
  TODO
  目前只做了单选，多选未加上

-->

<template>
  <el-select 
    v-model="currentVal" 
    size="small"
    filterable
    reserve-keyword
    placeholder="请输入关键词"
    :filter-method="handleFilter">
    <el-option v-for="(item,index) in list" :key="index" :label="item.name" :value="item.id" />
  </el-select>
</template>

<script>
export default {
  props:{
    value:{
      type: Number | String
    },
    api:{
      type: String,
    },
    options:{
      type: Object,
      default: () => {
        return {searchKey: 'name' ,id: 'id', name: 'name'}
      }
    },
  },
  data(){
    return{
      loading: false,
      list: [],
      t: null,
      time: 1000,
    }
  },
  computed:{
    currentVal:{
      get(){
        this.getPerson();
        return this.value;
      },
      set(newVal){
        let obj = this.list.find(item => item.id == newVal);
        this.$emit('update:value', newVal);
        this.$emit('change', obj);
      }
    }
  },
  methods:{
    handleFilter(query) {
      console.log(query);
      this.debounce(query.trim());
    },
    debounce(query){
      if(this.t){
        clearTimeout(this.t);
        this.t = null;
      }
      this.t = setTimeout(() => {
        this.getPerson(query);
      },this.time);
    },
    getPerson(query) {
      // if (query != '') {
        let params = {};
        params[this.options.searchKey] = query || null;
        this.$request('get', this.api, params, (data,msg) => {
          this.list = data.records.map(item => {
            item.id = item[this.options.id];
            item.name = item[this.options.name];
            return item;
          })
        });
      // }
    },
  }
}
</script>

<style>

</style>